package com.dcy.satoken.service;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import com.dcy.common.constant.RedisConstant;
import com.dcy.system.api.api.AuthApi;
import com.dcy.system.api.dto.out.RoleListOutDTO;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author dcy
 * @description sa-token权限实现类
 * @createTime 2022/12/29 11:38
 */
@RequiredArgsConstructor
@Component
public class StpInterfaceImpl implements StpInterface {

    @DubboReference
    private AuthApi authApi;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> permissionList = (List<String>) redisTemplate.opsForValue().get(RedisConstant.RESOURCE_CODE + loginId);
        if (CollUtil.isEmpty(permissionList)) {
            permissionList = authApi.getPermissionListByUserId((String) loginId);
            redisTemplate.opsForValue().set(RedisConstant.RESOURCE_CODE + loginId, permissionList, 1L, TimeUnit.DAYS);
        }
        return permissionList;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roleKeyList = (List<String>) redisTemplate.opsForValue().get(RedisConstant.ROLE_CODE + loginId);
        if (CollUtil.isEmpty(roleKeyList)) {
            roleKeyList = authApi.getAuthRoleListByUserId((String) loginId)
                    .stream()
                    .map(RoleListOutDTO::getRoleKey)
                    .collect(Collectors.toList());
            redisTemplate.opsForValue().set(RedisConstant.ROLE_CODE + loginId, roleKeyList, 1L, TimeUnit.DAYS);
        }
        return roleKeyList;
    }
}
